import dwUser from '@/models/dwUser';
import dayjs from 'dayjs';
import md5 from 'js-md5';
import { ObjectId } from 'mongodb';

// isDelete  0为启用  1为禁用

// 获取用户列表
export const getList = async (params) => {
  const { page, pageSize, ...others } = params;
  const query = { ...others };
  if (query.name) {
    query.name = new RegExp(params.name);
  }
  if (query.isDelete === 1 && (query.isDelete !== null || query.isDelete !== undefined)) {
    query.isDelete = params.isDelete;
  } else {
    query.isDelete = 0;
  }
  const res = await dwUser.getListPagination(query, { updateTime: -1 }, page, pageSize);
  return res;
};

// 添加用户
export const addUser = async (params) => {
  const { userName, name, role, isDelete, phone } = params;
  const res = await dwUser.findOne({ userName });
  if (res !== null) {
    return '用户已存在';
  }
  const password = md5('123456');
  const addData = {
    userName,
    name,
    password,
    role,
    isDelete,
    phone,
    updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    gmtCreated: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };
  await dwUser.insert(addData);
  return true;
};

// 获取用户详情
export const detailUser = async (params) => {
  const { personId } = params;
  const d = await dwUser.findOne({ _id: new ObjectId(personId) });
  if (d) {
    return d;
  }
  return '用户不存在';
};

// 修改用户
export const updateUser = async (params) => {
  const { userName, name, role, personId, phone, isDelete } = params;
  const d = await dwUser.update({ userName, name, role, phone, updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), isDelete }, { _id: new ObjectId(personId) });
  if (d) {
    return true;
  }
  return '修改失败';
};

// 启用停用用户
export const deleteUser = async (params) => {
  const { personId, isDelete } = params;
  const d = await dwUser.update({ isDelete, updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss') }, { _id: new ObjectId(personId) });
  if (d) {
    return true;
  }
  return '删除失败';
};

// 重置密码
export const resetPassword = async (params) => {
  const { personId, password } = params;
  const old: any = await dwUser.findOne({ _id: new ObjectId(personId) });
  if (old.password === password) {
    return {
      isError: true,
      message: '新旧密码一致',
    };
  }
  const d = await dwUser.update({ password, updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss') }, { _id: new ObjectId(personId) });
  if (d) {
    return {
      isError: false,
      data: true,
    };
  }
  return {
    isError: true,
    message: '重置密码失败',
  };
};
